﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QLNH.QLNH_BUS_WS;
using System.Threading;

namespace QLNH.MyLayouts
{
    public partial class LayoutCashier : LayoutUC
    {
        public LayoutCashier(MainForm mainForm)
        {
            this.mainForm = mainForm;
            InitializeComponent();
        }

        public override void OnReceivePackage(IRemoting.BasePackage package)
        {
            if (package.getBroadcastMassageHeader() == IRemoting.BroadcastMassgeHeader.SERVED_ORDER)
            {
                int orderNo = Int32.Parse(package.getBroadcastMassage());
                QLNH_BUS_WebServiceSoapClient ws = new QLNH_BUS_WebServiceSoapClient();

                OrderDetailDTO order = ws.GetOrder(orderNo);

                ListViewItem li = new ListViewItem()
                {
                    Text = order.TableID,
                    Name = order.OrderNo.ToString(),
                    ImageKey = "Served",
                    Tag = "NotSave"
                };

                li.SubItems.Add(order.OrderNo.ToString());
                lv_orders.BeginInvoke((MethodInvoker)(() => lv_orders.Items.Add(li)));
            }
        }

        // Get all order
        private void getAllOrder()
        {
            Thread t = new Thread(new ThreadStart(getAllOrderThread));
            t.SetApartmentState(ApartmentState.MTA);
            t.IsBackground = true;
            t.Start();
        }

        private void getAllOrderThread()
        {
            QLNH_BUS_WebServiceSoapClient ws = new QLNH_BUS_WebServiceSoapClient();
            OrderDetailDTO[] orders = ws.GetAllOrderForCashier();

            if (orders != null)
            {
                for (int i = 0; i < orders.Length; i++)
                {
                    ListViewItem li = new ListViewItem()
                    {
                        Text = orders[i].TableID,
                        Name = orders[i].OrderNo.ToString(),
                        ImageKey = "Served",
                        Tag = "NotSave"
                    };
                    li.SubItems.Add(orders[i].OrderNo.ToString());

                    lv_orders.BeginInvoke((MethodInvoker)(() => lv_orders.Items.Add(li)));
                }
            }
        }

        // Get order detail
        private void getOrderDetail()
        {
            lv_orderDetail.Items.Clear();

            Thread t = new Thread(new ThreadStart(getOrderDetailThread));
            t.SetApartmentState(ApartmentState.MTA);
            t.Start();
        }

        private void getOrderDetailThread()
        {
            int orderNo = -1;
            lv_orders.BeginInvoke((MethodInvoker)(()=> orderNo = Int32.Parse(lv_orders.SelectedItems[0].Name)));

            double total = 0.0F;

            Thread.Sleep(100);

            QLNH_BUS_WebServiceSoapClient ws = new QLNH_BUS_WebServiceSoapClient();
            OrderDetailDTO order = ws.GetOrder(orderNo);

            for (int i = 0; i < order.Meals.Count(); i++)
            {
                double price = ws.GetPrice(order.Meals[i].MealID);
                total += price * order.Meals[i].Amount;

                ListViewItem li = new ListViewItem()
                {
                    Text = order.Meals[i].MealName,
                    Name = order.Meals[i].MealID
                };
                li.SubItems.Add(order.Meals[i].Amount.ToString());
                li.SubItems.Add(price.ToString());

                lv_orderDetail.BeginInvoke((MethodInvoker)(() => lv_orderDetail.Items.Add(li)));
                lb_total.BeginInvoke((MethodInvoker)(() => lb_total.Text = total.ToString()));
            }

            tb_divideResult.BeginInvoke((MethodInvoker)(() => tb_divideResult.Text = (float.Parse(lb_total.Text) / float.Parse(numericUpDown.Value.ToString()) + "")));
        }

        private void LayoutCashier_Load(object sender, EventArgs e)
        {
            getAllOrder();
        }

        private void lv_orders_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lv_orders.SelectedItems.Count > 0)
            {
                ListViewItem li = lv_orders.SelectedItems[0];
                int orderNo = Int32.Parse(li.Name);

                    if (li.Tag.ToString().Equals("NotSave"))
                    {
                        bt_save.Enabled = true;
                        bt_print.Enabled = false;
                    }
                    else if (li.Tag.ToString().Equals("Saved"))
                    {
                        bt_save.Enabled = false;
                        bt_print.Enabled = true;
                    }

                    getOrderDetail();
            }
            else
            {
                bt_save.Enabled = false;
                bt_print.Enabled = false;
            }
        }

        private void numericUpDown_ValueChanged(object sender, EventArgs e)
        {
            tb_divideResult.Text = (float.Parse(lb_total.Text) / float.Parse(numericUpDown.Value.ToString())) + "";
        }

        private void bt_save_Click(object sender, EventArgs e)
        {
            bt_save.Enabled = false;
            lv_orders.SelectedItems[0].Tag = "Saved";

            QLNH_BUS_WebServiceSoapClient ws = new QLNH_BUS_WebServiceSoapClient();

            List<BillDetailDTO> billDetails = new List<BillDetailDTO>();

            for (int i = 0; i < lv_orderDetail.Items.Count; i++)
            {
                billDetails.Add(new BillDetailDTO()
                {
                    MealID = lv_orderDetail.Items[i].Name,
                    Amount = Int32.Parse(lv_orderDetail.Items[i].SubItems[1].Text),
                    Price = Double.Parse(lv_orderDetail.Items[i].SubItems[2].Text)
                });
            }

            if (ws.InsertBill(billDetails.ToArray<BillDetailDTO>()) == true)
            {
                MessageBox.Show("Lưu hóa đơn thành công");
            }
            else
            {
                MessageBox.Show("Lưu hóa đơn thất bại");
            }
        }

        private void bt_print_Click(object sender, EventArgs e)
        {
            if (lv_orders.SelectedItems.Count > 0)
            {
                ListViewItem li = lv_orders.SelectedItems[0];

                int orderNo = Int32.Parse(li.Name);
                string tableID = li.SubItems[0].Text;

                QLNH_BUS_WebServiceSoapClient ws = new QLNH_BUS_WebServiceSoapClient();
                ws.DeleteOrder(orderNo);

                // Send broadcast message
                mainForm.checkedOut(tableID);

                //print bill
                printDocument.Print();

                // Remove item in list view
                lv_orders.Items.Remove(lv_orders.Items.Find(orderNo.ToString(), false)[0]);

                // Reset control
                lv_orderDetail.Items.Clear();
                lb_total.Text = "0";
                tb_divideResult.Text = "0";
            }
        }

        private void printDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            QLNH_BUS_WebServiceSoapClient ws = new QLNH_BUS_WebServiceSoapClient();
            InfoDTO info = ws.GetInfo();

            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Near;
            sf.Trimming = StringTrimming.EllipsisCharacter;

            e.Graphics.DrawString(info.Name, new System.Drawing.Font("Pericles", 28F, FontStyle.Regular), Brushes.RoyalBlue, 100, 0, sf);
            e.Graphics.DrawString("Đt: " + info.PhoneNumber.ToString(), new System.Drawing.Font("Microsoft Sans Serif", 10F, FontStyle.Regular), Brushes.Black, 100, 50, sf);
            e.Graphics.DrawString("Đc: " + info.Address.ToString(), new System.Drawing.Font("Microsoft Sans Serif", 10F, FontStyle.Regular), Brushes.Black, 100, 80, sf);

            e.Graphics.DrawString("Nhân viên: " + mainForm.CurrentUser.FullName, new System.Drawing.Font("Microsoft Sans Serif", 10F, FontStyle.Regular), Brushes.Black, 100, 110, sf);

            string orderNo = lv_orders.SelectedItems[0].SubItems[1].Text;
            e.Graphics.DrawString("No: " + orderNo, new System.Drawing.Font("Microsoft Sans Serif", 10F, FontStyle.Regular), Brushes.Black, 400, 110, sf);

            int colNameWidth = 400;
            int colAmountWidth = 100;
            int colPriceWidth = 100;
            int rowHeight = 32;

            // Draw rect for columns name header
            e.Graphics.FillRectangle(Brushes.AliceBlue, 100, 150, colNameWidth, rowHeight);
            e.Graphics.DrawRectangle(Pens.Black, 100, 150, colNameWidth, rowHeight);
            e.Graphics.DrawString(lv_orderDetail.Columns[0].Text, lv_orderDetail.Font, Brushes.Black, 100, 150);

            // Draw rect for columns amount header
            e.Graphics.FillRectangle(Brushes.AliceBlue, colNameWidth, 150, colAmountWidth, rowHeight);
            e.Graphics.DrawRectangle(Pens.Black, colNameWidth, 150, colAmountWidth, rowHeight);
            e.Graphics.DrawString(lv_orderDetail.Columns[1].Text, lv_orderDetail.Font, Brushes.Black, colNameWidth, 150);

            // Draw rect for columns price header
            e.Graphics.FillRectangle(Brushes.AliceBlue, colNameWidth + colAmountWidth, 150, colPriceWidth, rowHeight);
            e.Graphics.DrawRectangle(Pens.Black, colNameWidth + colAmountWidth, 150, colPriceWidth, rowHeight);
            e.Graphics.DrawString(lv_orderDetail.Columns[2].Text, lv_orderDetail.Font, Brushes.Black, colNameWidth + colAmountWidth, 150);

            int actualHeight = 150 + rowHeight;

            for (int i = 0; i < lv_orderDetail.Items.Count; i++)
            {
                e.Graphics.DrawRectangle(Pens.Black, 100, actualHeight, colNameWidth, rowHeight);
                e.Graphics.DrawString(lv_orderDetail.Items[i].SubItems[0].Text, lv_orderDetail.Font, Brushes.Black, 100, actualHeight);

                e.Graphics.DrawRectangle(Pens.Black, colNameWidth, actualHeight, colAmountWidth, rowHeight);
                e.Graphics.DrawString(lv_orderDetail.Items[i].SubItems[1].Text, lv_orderDetail.Font, Brushes.Black, colNameWidth, actualHeight);

                e.Graphics.DrawRectangle(Pens.Black, colNameWidth + colAmountWidth, actualHeight, colPriceWidth, rowHeight);
                e.Graphics.DrawString(lv_orderDetail.Items[i].SubItems[2].Text, lv_orderDetail.Font, Brushes.Black, colNameWidth + colAmountWidth, actualHeight);

                actualHeight += rowHeight;
            }

            e.Graphics.DrawString("Tổng", lv_orderDetail.Font, Brushes.Black, colNameWidth, actualHeight);
            e.Graphics.DrawString(lb_total.Text, lv_orderDetail.Font, Brushes.Black, colNameWidth + colAmountWidth, actualHeight);

            printDialog.Document = printDocument;
            printDialog.ShowDialog();
        }
    }
}
